﻿using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace base31.Hub.Helpers
{
    public static class SHA1Hash
    {
        private static SHA1CryptoServiceProvider _cryptoTransformSHA1;

        public static SHA1CryptoServiceProvider CryptoProvider
        {
            get { return _cryptoTransformSHA1 ?? (_cryptoTransformSHA1 = new SHA1CryptoServiceProvider()); }
        }

        public static int GetSHA1HashToInt(this string stringToHash)
        {
            return string.IsNullOrWhiteSpace(stringToHash) ? 0 : (HashToInt(stringToHash, Encoding.Default));
        }

        public static string GetSHA1HashToString(this string stringToHash)
        {
            return string.IsNullOrWhiteSpace(stringToHash) ? String.Empty : (HashToString(stringToHash, Encoding.Default));
        }

        private static int HashToInt(string stringToHash, Encoding enc)
        {
            return BitConverter.ToInt32(CryptoProvider.ComputeHash(enc.GetBytes(stringToHash)), 0);
        }

        private static string HashToString(string stringToHash, Encoding enc)
        {
            return BitConverter.ToString(CryptoProvider.ComputeHash(enc.GetBytes(stringToHash)), 0);
        }

        public static string HMACSHA1ToString(this string input, byte[] key)
        {
            var hmacsha1 = new HMACSHA1(key);
            byte[] byteArray = Encoding.ASCII.GetBytes(input);
            var stream = new MemoryStream(byteArray);
            return hmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
        }

    }
}